package com.xcc.common;

import com.sun.org.apache.regexp.internal.RE;
import com.xcc.exception.ParamException;
import com.xcc.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @outhor Ren
 * @create 2019-03-20 19:12
 * 描述:
 * 全局异常处理
 */
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {

    @Nullable
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         @Nullable Object o, Exception e) {
        String url = request.getRequestURL().toString();
        ModelAndView mv = null;
        String defualtMsg = "System errror";

        log.error("unknown exception, url: " + url, e);

        // 设定规则,请求获取页面时,以 .page 结尾.
        if (url.endsWith(".page")) {
            Result result = Result.fial(-1, "error");
            // 会跳转至 exception.jsp 页面, 如果没有需要创建该页面.
            // 可跳转至其他页面
            return new ModelAndView("exception", result.toMap());
        }

        // 判断异常类型
        if (e instanceof PermissionException | e instanceof ParamException) {
            // 对应 spring-servlet.xml 中的 jsonView 解析器
            Result result = Result.fial(2, e.getMessage());
            mv = new ModelAndView("jsonView", result.toMap());
        } else {
            // 对应 spring-servlet.xml 中的 jsonView 解析器
            Result result = Result.fial(-1, "system error");
            mv = new ModelAndView("jsonView", result.toMap());
        }
        return mv;
    }
}
